<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 6.1</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="6.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="6.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#6">Chapter 6. More about Functions</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><a name="closures"><h2>6.1 &ndash; Closures</h2></a>

<p>When a function is written enclosed in another function,
it has full access to local variables from the enclosing function;
this feature is called <em>lexical scoping</em>.
Although that may sound obvious, it is not.
Lexical scoping, plus first-class functions,
is a powerful concept in a programming language,
but few languages support that concept.

<p>Let us start with a simple example.
Suppose you have a list of student names
and a table that associates names to grades;
you want to sort the list of names,
according to their grades (higher grades first).
You can do this task as follows:

<pre>
    names = {"Peter", "Paul", "Mary"}
    grades = {Mary = 10, Paul = 7, Peter = 8}
    table.sort(names, function (n1, n2)
      return grades[n1] > grades[n2]    -- compare the grades
    end)
</pre>
Now, suppose you want to create a function to do this task:
<pre>
    function sortbygrade (names, grades)
      table.sort(names, function (n1, n2)
        return grades[n1] > grades[n2]    -- compare the grades
      end)
    end
</pre>
The interesting point in the example is that
the anonymous function given to <code>sort</code>
accesses the parameter <code>grades</code>,
which is local to the enclosing function <code>sortbygrade</code>.
Inside this anonymous function,
<code>grades</code> is neither a global variable nor a local variable.
We call it an <em>external local variable</em>,
or an <em>upvalue</em>.
(The term "upvalue" is a little misleading,
because <code>grades</code> is a variable, not a value.
However, this term has historical roots in Lua
and it is shorter than "external local variable".)

<p>Why is that so interesting?
Because functions are first-class values.
Consider the following code:
<pre>
    function newCounter ()
      local i = 0
      return function ()   -- anonymous function
               i = i + 1
               return i
             end
    end
    
    c1 = newCounter()
    print(c1())  --> 1
    print(c1())  --> 2
</pre>
Now, the anonymous function uses an upvalue, <code>i</code>,
to keep its counter.
However, by the time we call the anonymous function,
<code>i</code> is already out of scope,
because the function that created that variable
(<code>newCounter</code>) has returned.
Nevertheless, Lua handles that situation correctly,
using the concept of <em>closure</em>.
Simply put, a closure is a function plus all it
needs to access its upvalues correctly.
If we call <code>newCounter</code> again,
it will create a new local variable <code>i</code>,
so we will get a new closure,
acting over that new variable:
<pre>
    c2 = newCounter()
    print(c2())  --> 1
    print(c1())  --> 3
    print(c2())  --> 2
</pre>
So, <code>c1</code> and <code>c2</code> are different closures
over the same function
and each acts upon an independent
instantiation of the local variable <code>i</code>.
Technically speaking, what is a value in Lua is the closure,
not the function.
The function itself is just a prototype for closures.
Nevertheless, we will continue to use the term "function" to
refer to a closure whenever there is no possibility of confusion.

<p>Closures provide a valuable tool in many contexts.
As we have seen,
they are useful as arguments to higher-order functions
such as <code>sort</code>.
Closures are valuable for functions that build other functions too,
like our <code>newCounter</code> example;
this mechanism allows Lua programs to incorporate
fancy programming techniques from the functional world.
Closures are useful for <em>callback</em> functions, too.
The typical example here occurs
when you create buttons in a typical GUI toolkit.
Each button has a callback function to be called
when the user presses the button;
you want different buttons to do slightly different things when pressed.
For instance, a digital calculator needs ten similar buttons,
one for each digit.
You can create each of them with a function like the next one:
<pre>
    function digitButton (digit)
      return Button{ label = digit,
                     action = function ()
                                add_to_display(digit)
                              end
                   }
    end
</pre>
In this example, we assume that <code>Button</code> is a toolkit function
that creates new buttons;
<code>label</code> is the button label;
and <code>action</code> is the callback function
to be called when the button is pressed.
(It is actually a closure,
because it accesses the upvalue <code>digit</code>.)
The callback function can be called
a long time after <code>digitButton</code> did its task and
after the local variable <code>digit</code> went out of scope,
but it can still access that variable.

<p>Closures are valuable also in a
quite different context.
Because functions are stored in regular variables,
we can easily redefine functions in Lua,
even predefined functions.
This facility is one of the reasons Lua is so flexible.
Frequently, however, when you redefine a function you need
the original function in the new implementation.
For instance, suppose you want to redefine the function <code>sin</code> to
operate in degrees instead of radians.
This new function must convert its argument,
and then call the original <code>sin</code> function to do the real work.
Your code could look like
<pre>
    oldSin = math.sin
    math.sin = function (x)
      return oldSin(x*math.pi/180)
    end
</pre>
A cleaner way to do that is as follows:

<pre>
    do
      local oldSin = math.sin
      local k = math.pi/180
      math.sin = function (x)
        return oldSin(x*k)
      end
    end
</pre>
Now, we keep the old version in a private variable;
the only way to access it is through the new version.

<p>You can use this same feature to create secure environments,
also called <em>sandboxes</em>.
Secure environments are essential when running untrusted code,
such as code received through the Internet by a server.
For instance, to restrict the files a program can access,
we can redefine the <code>open</code> function
(from the <code>io</code> library) using closures:
<pre>
    do
      local oldOpen = io.open
      io.open = function (filename, mode)
        if access_OK(filename, mode) then
          return oldOpen(filename, mode)
        else
          return nil, "access denied"
        end
      end
    end
</pre>
What makes this example nice is that, after that redefinition,
there is no way for the program to call the unrestricted <code>open</code>,
except through the new, restricted version.
It keeps the insecure version as a private variable in a closure,
inaccessible from the outside.
With this facility, you can build Lua sandboxes in Lua itself,
with the usual benefit: flexibility.
Instead of a one-size-fits-all solution,
Lua offers you a meta-mechanism,
so that you can tailor your environment for your specific security needs.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="6.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

